package com.mgq.netty.chat.handler;

import com.mgq.netty.chat.message.LoginRequestMessage;
import com.mgq.netty.chat.message.LoginResponseMessage;
import com.mgq.netty.chat.service.UserServiceFactory;
import com.mgq.netty.chat.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author MaGuangQi
 * @description
 * @date 2021-12-07 17:17
 **/
@ChannelHandler.Sharable
public class LoginRequestMessageHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {

    /**
     *  处理登录请求
     * @param ctx c
     * @param msg msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean login = UserServiceFactory.getUserService().login(username, password);
        //登录成功
        LoginResponseMessage responseMessage;
        if (login) {
            responseMessage = new LoginResponseMessage(true, "登录成功");
            SessionFactory.getSession().bind(ctx.channel(), username);
        } else {
            responseMessage = new LoginResponseMessage(false, "登录失败");
        }
        ctx.writeAndFlush(responseMessage);
    }
}
